package com.lines.chap03;

/**
 * <p>
 * <code>LoopLinkedList</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-04-03 10:07
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class LoopLinkedList {
    private Node head;

    public static void main(String[] args) {
        new LoopLinkedList().method(6,5);
    }

    public void method(int n,int m){
        //n个人围成一圈，第M个被杀掉
        for (int i = 0; i < n; i++) {
            insertTail(i+1);//组成一个链表
        }
        printf();
        System.out.println("----------------------");
        methodForDel(m);
        printf();


    }

    public void printf(){
        Node cur = head;
        do {
            System.out.print(cur.value);
            cur = cur.next;
        }while (cur!=head);
    }

    private void methodForDel(int m) {
        while (true){
            Node delPre = head;
            for (int i = 2; i <m; i++) {//找到待删除节点的前一个节点
                delPre = delPre.next;

            }
            System.out.println("删除节点："+delPre.next.value);
            delPre.next = delPre.next.next;
            head=delPre.next;//每次删除完，把删除完的下一个节点设置为头节点

            if (head==head.next){//头节点的下一个节点还是头节点，表示链表就剩下头节点了，退出循环
                break;
            }
        }
    }

    //尾插法
    public void insertTail(int data){
        Node node = new Node(data);
        if (head==null){//链表没有节点
            head = node;
            node.next=node;
        }else if(head==head.next){//链表有一个节点
            head.next=node;
            node.next=head;
        }else {//链表有很多节点，找到尾结点
            Node tail = head;
            while (tail.next!=head){
                tail = tail.next;
            }
            tail.next=node;
            node.next=head;
        }
    }

    private static class Node{
        int value;
        Node next;

        public Node(int value) {
            this.value = value;
            this.next = null;
        }
    }
}
